<?php
class Login extends Controller
{
    public function actionLogin()
    {
        if ($this->_session->get('customerId'))
        {
            return $this->responseRedirect('account');
        }

        $this->setTitle('Đăng nhập');

        $this->setBreadcrumb(array(
            array(
                'title' => 'Trang chủ',
                'link' => Link::build(''),
                'index' => true,
            ),
            array(
                'title' => 'Đăng nhập',
                'link' => Link::build('login/login'),
            )
        ));

        $this->loadChildControllers(array(
            'header' => 'module/Header',
            'footer' => 'module/Footer',

            // right sidebar
            'accountMenu' => 'module/AccountMenu'
        ));

        $email = $this->_input->filterSingle('email', Input::STRING);

        // don't log in
        if (!$email)
        {
            return $this->responseView('login/form', array(), 'layout/right_sidebar');
        }
        // login
        else
        {
            $userModel = $this->_loader->model('CustomerModel');

            $userInput = $this->_input->filter(array(
                'email' => Input::STRING,
                'password' => Input::STRING
            ));

            if ($user = $userModel->login($userInput['email'], $userInput['password']))
            {
                $this->_session->set('customerId', $user['customer_id']);

                return $this->responseRedirect('account');
            }

            $viewParams = array(
                'email' => $email,
                'error' => 'Tài khoản hoặc mật khẩu không chính xác.'
            );

            return $this->responseView('login/form', $viewParams, 'layout/right_sidebar');
        }
    }

    public function actionLogout()
    {
        $this->_session->set('customerId', false);

        return $this->responseRedirect('login/login');
    }
}